package cn.car.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

@Slf4j
public class Base64ToImageUtil {

    // 将base64字符串保存为图片文件
    public static void saveBase64ImageToFile(String base64String, String filePath) throws IOException {
        if (StrUtil.isEmpty(base64String)) {
            log.info("[Base64ImageToFile] base64String is null filePath:{}", filePath);
        }
        byte[] imageBytes = decodeBase64(base64String);
        saveImage(imageBytes, filePath);
    }

    // 将base64字符串转换为字节数组
    public static byte[] decodeBase64(String base64String) {
        return Base64.getDecoder().decode(base64String);
    }

    // 将字节数组保存为文件
    public static void saveImage(byte[] imageBytes, String filePath) throws IOException {
        final File dest = new File(filePath);
        final File parentFile = dest.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(imageBytes);
        }
    }

    public static String imageToBase64(String imagePath) {
        if (StrUtil.isEmpty(imagePath)) {
            return null;
        }

        if (imagePath.startsWith("MOCK_BASE64") || imagePath.equals("\\Users\\yp-220616\\hj\\123.jpg") || imagePath.equals("/Users/yp-220616/hj/123.jpg")) {
            return "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAXABoDASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAAAAcIBAb/xAAlEAACAwABBAICAwEAAAAAAAADBAECBQYAERMUByISFRYhIyT/xAAXAQEBAQEAAAAAAAAAAAAAAAAFBAIJ/8QAJhEAAgEDAwMEAwAAAAAAAAAAAQIDBBEhAAUSE0FRB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));
    }

    public static String imageToBase64(File file) {
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            // 将文件内容读取到字节数组
            byte[] imageData = new byte[(int) file.length()];
            imageInFile.read(imageData);

            // 使用 Base64 编码字节数组
            return bytesToBase64(imageData);
        } catch (Exception e) {
            log.error("[imageToBase64] error. msg:{}", e.getMessage());
            return null;
        }
    }

    public static String bytesToBase64(byte[] data) {
        return Base64.getEncoder().encodeToString(data);
    }

    // 图片转base64, 支持压缩图片到指定大小以下
    public static String imageToBase64(String imagePath, long maxBytes) {
        if (StrUtil.isEmpty(imagePath)) {
            return null;
        }
        final File file = new File(imagePath);
        if (!file.exists()) {
            log.error("[imageToBase64] File not found: {}", imagePath);
            return null;
        }

        try {
            // 读取图片文件
            final BufferedImage originalImage = ImageIO.read(file);
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (file.length() <= maxBytes) {
                // 图片无需压缩，直接写入输出流
                return imageToBase64(imagePath);
            }
            final long start = System.currentTimeMillis();
            log.info("[imageToBase64] Image size is too large, max:{}, imgSize:{}, compressing: {}", maxBytes, file.length(), imagePath);
            // 如果图片大于指定的大小, 进行压缩
            // 计算缩放比例
            final double ratio = (double) maxBytes / file.length();
            final int width = (int) (originalImage.getWidth() * Math.sqrt(ratio));
            final int height = (int) (originalImage.getHeight() * Math.sqrt(ratio));

            // 创建缩小后的图片
            final Image scaledImage = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            final BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(scaledImage, 0, 0, null);
            g.dispose();

            // 将压缩后的图片写入输出流
            ImageIO.write(resizedImage, "jpg", baos);
            final byte[] imageBytes = baos.toByteArray();
            final String base64 = bytesToBase64(imageBytes);
            log.info("[imageToBase64] Image compressed successfully, max:{},  imgSize:{}, afterSize:{}, cost: {}ms", maxBytes, file.length(), imageBytes.length, System.currentTimeMillis() - start);
            return base64;
        } catch (IOException e) {
            log.error("[imageToBase64] Error converting image to Base64", e);
            return null;
        }
    }


    public static String imageToBase64LimitSize(String imagePath) {
        return imageToBase64(imagePath, 2 * 1024 * 1024L);
    }
}
